<template>
    <div :class="$style.cards">
        <a-card title="可提现金额" :class="$style.card">
            <div>
                <span :class="$style.amount">{{ amount }}</span>元
            </div>
            <div class="m-t-20">
                <a-button type="primary" size="small" :disabled="amount <= 0" @click="openWithdrawal">提现</a-button>
            </div>
        </a-card>
        <a-card title="累计提现金额" :class="$style.card">
            <span :class="$style.amount">{{ withdrawalAmount }}</span>元
        </a-card>
        <a-card title="提现账号" :class="$style.card">
            <template v-if="!editing" #extra><a-button type="text" @click="openeditPayee">编辑</a-button></template>
            <a-form ref="payeeFormRef" :label-col="{ span: 4 }" labelAlign="left">
                <a-form-item :class="$style.payeeitem" label="开户银行">
                    <a-input v-if="editing" v-model:value="payeeFormData.bank" show-count :maxlength="20" />
                    <span v-else>{{ payeeData.bank }}</span>
                </a-form-item>
                <a-form-item :class="$style.payeeitem" label="开户人">
                    <a-input v-if="editing" v-model:value="payeeFormData.payee" show-count :maxlength="10" />
                    <span v-else>{{ payeeData.payee }}</span>
                </a-form-item>
                <a-form-item :class="$style.payeeitem" label="卡号账号">
                    <a-input v-if="editing" v-model:value="payeeFormData.account" show-count :maxlength="20" />
                    <span v-else>{{ payeeData.account }}</span>
                </a-form-item>
                <a-form-item v-if="editing" :class="$style.payeeitem" :wrapper-col="{ offset: 4 }">
                    <a-button style="margin-left: 10px" @click="cancelPayee">取消</a-button>
                    <a-button type="primary" class="m-l-10" @click="submitPayee">保存</a-button>
                </a-form-item>
            </a-form>
        </a-card>
    </div>

    <a-tabs class="m-t-20">
        <a-tab-pane key="1" tab="提现记录">
            <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='page' :rowSelection="false">
                <template #bank="{ record }">
                    <div>银行：{{ record.bank }}</div>
                    <div>收款人：{{ record.payee }}</div>
                    <div>账号：{{ record.account }}</div>
                </template>

                <template #status="{record}">
                    <template v-if="record.status == 0">{{ WITHDRAWAL_STATUS[record.status] }}</template>
                    <template v-else-if="record.status == 1"><a-tag color="success">{{ WITHDRAWAL_STATUS[record.status] }}</a-tag></template>
                    <template v-else-if="record.status == 2"><a-tag color="error">{{ WITHDRAWAL_STATUS[record.status] }}</a-tag></template>
                    <template v-else-if="record.status == 3"><a-tag>{{ WITHDRAWAL_STATUS[record.status] }}</a-tag></template>
                </template>

                <template #$action="{record, index}">
                    <BTextButton v-if="record.status == 0" @click="revokeApply(record.id)">撤销</BTextButton>
                </template>
                
            </BPTable>
        </a-tab-pane>
    </a-tabs>

    <BDialog v-model:visible='withdrawalVisible' title="申请提现" width='500px' :confirm='withdrawalSubmit'>
        <a-input type="number" placeholder="提现金额" v-model:value="applyAmount" />
    </BDialog>

</template>

<script lang="ts" setup>
    import { accountApi, applyWithdrawalApi, applyWithdrawalRecordPageApi, revokeApplyApi, updatePayeeApi } from '@/api/merchant/Merchant';
import { WITHDRAWAL_STATUS } from '@/constant';
import { parseTime } from '@/utils';
    import { Modal, message } from 'ant-design-vue';
import dayjs from 'dayjs';
    import { ref } from 'vue';
    
    const payeeFormRef = ref()
    const editing = ref(false)
    const payeeFormData = ref<any>({});
    const payeeData = ref({
        account : '',
        bank : '',
        payee : ''
    })
    function openeditPayee() {
        payeeFormData.value = {...payeeData.value}
        editing.value = true
    }
    function cancelPayee(){
        editing.value = false
    }

    async function submitPayee() {
        const r = await updatePayeeApi(payeeFormData.value)
        if(r.success) {
            payeeData.value = {...payeeFormData.value}
            message.success('保存成功')
            editing.value = false
        }else {
            message.error('保存失败')
        }
        
    }

    const amount = ref(0)
    const withdrawalAmount = ref(0)


    const withdrawalVisible = ref(false)
    const applyAmount = ref()
    function openWithdrawal() {
        applyAmount.value = ''
        withdrawalVisible.value = true
    }
    async function withdrawalSubmit() {
        const am = Number(applyAmount.value)
        if(am <= 0) {
            message.error('请填写正确的提现金额')
            return
        }

        if(am > amount.value) {
            message.error('可提现金额不足')
            return
        }

        const r = await applyWithdrawalApi(am)
        if(r.success) {
            queryAccount()
            tableRef.value.reload()
            message.success('申请成功')
            withdrawalVisible.value = false
        }else {
            message.error(r.msg)
        }
    }
    

    function queryAccount(){
        accountApi().then(res => {
            payeeData.value.account = res.data.account
            payeeData.value.bank = res.data.bank
            payeeData.value.payee = res.data.payee

            amount.value = Number(res.data.amount)
            withdrawalAmount.value = Number(res.data.withdrawalAmount)
        })
    }
    


    const tableRef = ref()
    function page(data){
        const {createTime, ...params} = data
        if(createTime) {
            params.startTime = dayjs(createTime[0]).unix()
            params.endTime = dayjs(createTime[1]).unix()
        }
        return applyWithdrawalRecordPageApi(params)
    }


    function revokeApply(id:number) {
        Modal.confirm({
            title : '确定撤销吗',
            async onOk() {
                const r = await revokeApplyApi(id)
                if(r.success) {
                    message.success('撤销成功')
                    queryAccount()
                    tableRef.value.reload()
                }else {
                    message.error(r.msg)
                }
            }
        })
    }

    const columns = ref<Column[]>([
        {
            title : '金额(元)',
            dataIndex : 'amount',
            align : 'center',
        },

        {
            title : '申请人',
            dataIndex : 'member',
            align : 'center',
        },

        {
            title : '收款信息',
            dataIndex : 'bank',
            align : 'center',
        },

        {
            title : '状态',
            dataIndex : 'status',
            align : 'center',
            inSearch : true,
            type : 'select',
            options : WITHDRAWAL_STATUS
        },

        {
            title : '原因',
            dataIndex : 'reason',
        },

        {
            title : '审批时间',
            dataIndex : 'completeTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },


        {
            title : '申请时间',
            dataIndex : 'createTime',
            align : 'center',
            inSearch : true,
            type : 'rangePicker',
            customRender({text}) {
                return parseTime(text)
            }
        },

        {
            title : '操作',
            dataIndex : '$action',
            align : 'center'
        }
    ])




    queryAccount()

</script>

<style lang="scss" module>
    .cards{
        display: flex;
        gap: 30px;

        .card{
            flex: 1;
        }

        .amount{
            font-size: 24px;
            font-weight: bold;
        }
    }

    .payeeitem{
        margin-bottom: 8px;
        &:last-of-type{
            margin-bottom: 0;
        }
    }
</style>